package com.lightboat.common.manager;

import cn.hutool.extra.spring.SpringUtil;
import com.lightboat.common.utils.Threads;
import com.lightboat.common.utils.spring.SpringUtils;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.TimerTask;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

/**
 * 异步任务管理器
 *
 * @author lightboat
 */
public class AsyncManager {
    private static AsyncManager me = new AsyncManager();
    /**
     * 操作延迟10毫秒
     */
    private final int OPERATE_DELAY_TIME = 10;

    /**
     * 异步操作任务调度线程池
     */
    private ScheduledExecutorService executor = SpringUtils.getBean("scheduledService");
    private ThreadPoolTaskExecutor taskExecutor = SpringUtil.getBean("threadPoolTask");

    /**
     * 单例模式
     */
    private AsyncManager() {
    }

    public static AsyncManager me() {
        return me;
    }

    /**
     * 执行任务
     *
     * @param task 任务
     */
    public void execute(TimerTask task) {
        executor.schedule(task, OPERATE_DELAY_TIME, TimeUnit.MILLISECONDS);
    }

    /**
     * 执行任务
     * @param task 任务
     * @param time  时间 单位毫秒
     */
    public void execute(TimerTask task,long time) {
        executor.schedule(task, time, TimeUnit.MILLISECONDS);
    }

    /**
     * 执行任务
     * @param task
     */
    public void execute(Supplier<?> task) {
        taskExecutor.execute(task::get);
    }

    /**
     * 执行任务
     * @param task 任务
     * @param isStart 是否启动
     */

    public void execute(Supplier<?> task,boolean isStart) {
        if (isStart) {
            taskExecutor.execute(task::get);
        }
    }

    /**
     * 停止任务线程池
     */
    public void shutdown() {
        Threads.shutdownAndAwaitTermination(executor);
        taskExecutor.shutdown();
    }
}
